﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cars
{
    public class KslCarInfo : CarInfo
    {
        override public void ParseListView(string source)
        {
            ParseAdId(source);
            ParseYearMakeAndModel(source);
            ParsePrice(source);
            ParseDescription(source);
        }

        public override void ParseDetailView(string source)
        {
            
        }

        private void ParseAdId(string source)
        { 
            // we want to be positioned after the = sign, so add 4
            int startIdx_AdId = find(source, 0, "&ad=") + 4;
            int endIdx_AdId = find(source, startIdx_AdId, '"');

            this.AdId = copyFrom(source, startIdx_AdId, endIdx_AdId);         
        }

        private void ParseYearMakeAndModel(string source)
        {
            TextBlock yearMakeAndModelBlock = getTextBlock(source, 0, "<span class=\"adTitle\">", true);

            // first get the year
            // <span style="color: #000;">2005</span>
            TextBlock yearBlock = getTextBlock(yearMakeAndModelBlock.Text, 0, "<span style=\"color: #000;\">", true);                                                                            
            this.Year = int.Parse(yearBlock.Text);

            // starting after the close of the span above...
            // </span> - GMC Denali</a>
            // magic number 11 skips the "</span> -  "
            int beginIdx_Make = yearBlock.EndIdx + 11;
            int endIdx_Make = find(yearMakeAndModelBlock.Text, beginIdx_Make, ' ');
            this.Make = copyFrom(yearMakeAndModelBlock.Text, beginIdx_Make, endIdx_Make);

            // make starts after model and ends with </a>
            int beginIdx_Model = endIdx_Make + 1;
            int endIdx_Model = find(yearMakeAndModelBlock.Text, beginIdx_Model, '<');
            this.Model = copyFrom(yearMakeAndModelBlock.Text, beginIdx_Model, endIdx_Model);
        }

        private void ParsePrice(string source)
        {
            TextBlock priceBlock = getTextBlock(source, 0, "<div class=\"priceBox\">", true);

            // looking for this block:
            // $4,795<span class="priceCents">00</span>
            int beginIdx_Dollars = find(priceBlock.Text, 0, '$') + 1;
            int endIdx_Dollars = find(priceBlock.Text, beginIdx_Dollars, '<');

            string dollarString = copyFrom(priceBlock.Text, beginIdx_Dollars, endIdx_Dollars);
            TextBlock centBlock = getTextBlock(priceBlock.Text, 0, "<span class=\"priceCents\">", true);

            this.Price = decimal.Parse(dollarString + "." + centBlock.Text);
        }

        private void ParseDescription(string source)
        {
            TextBlock descriptionBlock = getTextBlock(source, 0, "<div class=\"adDesc\">", true);
            this.Description = descriptionBlock.Text;
        }
    }
}
